import turf from '@turf/turf'
/**
* 修复版Leaflet测量工具
* @param {L.Map} mapObj - 已初始化的Leaflet地图对象
* @returns {Object} 测量工具API
*/
export function addLeafletMeasureTool(mapObj) {
 // 获取当前主题
 const getTheme = () => document.body.classList.contains('theme-white') ? 'white' : 'black';

 // 主题颜色配置
 const themeColors = {
   black: {
     primary: '#2d8cf0',
     bg: '#1e2121',
     text: '#f5f7fa',
     hover: '#363e4f'
   },
   white: {
     primary: '#1890ff',
     bg: '#ffffff',
     text: '#333333',
     hover: '#40a9ff'
   }
 };

 // 当前状态
 let colors = themeColors[getTheme()];
 let isMeasuring = false;
 let currentMode = null;
 let points = [];
 let tempPoint = null;
 const markers = L.layerGroup({pane: 'popupPane'}).addTo(mapObj); // 使用popupPane确保在最上层
 const lines = L.layerGroup({pane: 'popupPane'}).addTo(mapObj); // 使用popupPane确保在最上层
 let resultDiv = null;
 let mouseMoveHandler = null;
 let clickHandler = null;
 let dblClickHandler = null;
 let tempLine = null;

 // 创建结果展示元素
 function createResultDiv() {
   if (!resultDiv) {
     resultDiv = L.DomUtil.create('div', 'leaflet-measure-result');
     resultDiv.style.cssText = `
       position: absolute;
       top: 20px;
       left: 50%;
       transform: translateX(-50%);
       background-color: ${colors.bg};
       color: ${colors.text};
       padding: 8px 16px;
       padding-right: 36px;
       border-radius: 4px;
       border: 1px solid ${colors.primary};
       z-index: 1001; // 设置更高的z-index
       font-size: 14px;
       box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
       max-width: 80%;
       text-align: center;
     `;

     // 阻止地图事件
     L.DomEvent.disableClickPropagation(resultDiv);
     L.DomEvent.disableScrollPropagation(resultDiv);

     // 添加关闭按钮
     const closeButton = L.DomUtil.create('div', 'leaflet-measure-close', resultDiv);
     closeButton.innerHTML = '×';
     closeButton.style.cssText = `
       position: absolute;
       right: 8px;
       top: 50%;
       transform: translateY(-50%);
       cursor: pointer;
       font-size: 18px;
       width: 20px;
       height: 20px;
       line-height: 18px;
       text-align: center;
       border-radius: 50%;
       transition: all 0.2s;
     `;

     // 鼠标悬停效果
     closeButton.onmouseover = () => {
       closeButton.style.backgroundColor = colors.hover;
     };
     closeButton.onmouseout = () => {
       closeButton.style.backgroundColor = 'transparent';
     };

     // 点击关闭按钮事件
     // 点击关闭按钮事件
     closeButton.onclick = (e) => {
       // 阻止事件冒泡
       e.stopPropagation();
       L.DomEvent.stop(e);
       // 清除所有测量图层
       markers.clearLayers();
       lines.clearLayers();
       reset();
       hideResult();
       // 重新开始测量
       if (currentMode === 'distance') {
         showResult('点击地图开始测量距离，双击结束');
       } else if (currentMode === 'area') {
         showResult('点击地图开始测量面积，双击结束');
       }
     };

     mapObj.getContainer().appendChild(resultDiv);
   }
   return resultDiv;
 }

 // 显示测量结果
 function showResult(text) {
   const div = createResultDiv();
   // 创建文本容器
   if (!div.querySelector('.measure-text')) {
     const textDiv = L.DomUtil.create('div', 'measure-text', div);
     textDiv.style.display = 'inline-block';
   }
   div.querySelector('.measure-text').textContent = text;
   div.style.display = 'block';
 }

 // 隐藏结果
 function hideResult() {
   if (resultDiv) resultDiv.style.display = 'none';
 }

 // 添加测量点
 function addPoint(latlng) {
   points.push(latlng);

   // 添加标记点
   const marker = L.circleMarker(latlng, {
     radius: 5,
     fillColor: colors.primary,
     color: '#fff',
     weight: 1,
     opacity: 1,
     fillOpacity: 0.8
   }).addTo(markers);

   // 绘制固定线段和多边形（当有多个点时）
   if (points.length > 1) {
     if (currentMode === 'distance') {
       // 距离测量只画线
       const lastPoint = points[points.length - 2];
       L.polyline([lastPoint, latlng], {
         color: colors.primary,
         weight: 2
       }).addTo(lines);
     } else if (currentMode === 'area' && points.length > 2) {
       // 面积测量画填充多边形
       lines.clearLayers(); // 清除之前的线
       L.polygon(points, {
         color: colors.primary,
         weight: 2,
         fillColor: colors.primary,
         fillOpacity: 0.2
       }).addTo(lines);
     } else {
       // 面积测量但点数不足时只画线
       const lastPoint = points[points.length - 2];
       L.polyline([lastPoint, latlng], {
         color: colors.primary,
         weight: 2
       }).addTo(lines);
     }
   }

   return marker;
 }

 // 更新临时线段
 function updateTempLine(latlng) {
   if (!points.length || !isMeasuring) return;

   if (!tempLine) {
     tempLine = L.polyline([], {
       color: colors.primary,
       weight: 2,
       dashArray: '5, 10'
     }).addTo(lines);
   }

   const lastPoint = points[points.length - 1];
   tempLine.setLatLngs([lastPoint, latlng]);

   // 如果是面积测量且有足够的点，显示临时多边形
   if (currentMode === 'area' && points.length > 2) {
     lines.clearLayers(); // 清除之前的线
     const tempPoints = [...points, latlng, points[0]]; // 闭合多边形
     L.polygon(tempPoints, {
       color: colors.primary,
       weight: 2,
       fillColor: colors.primary,
       fillOpacity: 0.2,
       dashArray: '5, 10',
       interactive: false
     }).addTo(lines);
   }
 }

 // 计算距离（米）
 function calculateDistance(points, includeTempPoint = false) {
   let total = 0;
   const pointsToUse = includeTempPoint && tempPoint
     ? [...points, tempPoint] : points;

   for (let i = 1; i < pointsToUse.length; i++) {
     total += mapObj.distance(pointsToUse[i - 1], pointsToUse[i]);
   }
   return total;
 }

 // 计算面积（平方米）
 function calculateArea(points, tempLatLng = null) {
   if (points.length < 3) return 0;

   // 创建用于计算的点数组
   let calcPoints = [...points];

   // 如果有临时点，添加到计算中
   if (tempLatLng) {
     calcPoints.push(tempLatLng);
   }

   // 确保多边形闭合（首尾相连）
   if (calcPoints[0] !== calcPoints[calcPoints.length - 1]) {
     calcPoints.push(calcPoints[0]);
   }

   try {
     // 计算多边形面积
     let area = 0;
     for (let i = 0; i < calcPoints.length - 1; i++) {
       const p1 = calcPoints[i];
       const p2 = calcPoints[i + 1];
       // 使用投影坐标计算面积
       area += (p1.lng * p2.lat - p2.lng * p1.lat);
     }
     // 取绝对值并除以2
     area = Math.abs(area) / 2;

     // 由于使用的是投影坐标，结果已经是平方米
     return area;
   } catch (error) {
     console.error('Error calculating area:', error);
     return 0;
   }
 }

 // 实时计算测量结果
 function calculateMeasurement(tempLatLng = null) {
   if (currentMode === 'distance') {
     const distance = calculateDistance(points, tempLatLng !== null);
     showResult(distance < 1000
       ? `距离: ${distance.toFixed(2)} 米`
       : `距离: ${(distance / 1000).toFixed(3)} 公里`);
   } else if (currentMode === 'area' && points.length > 2) {
     const area = calculateArea(points, tempLatLng);
     if (area < 10000) {
       showResult(`面积: ${area.toFixed(2)} 平方米`);
     } else if (area < 1000000) {
       showResult(`面积: ${(area / 10000).toFixed(4)} 公顷`);
     } else {
       showResult(`面积: ${(area / 1000000).toFixed(4)} 平方公里`);
     }
   }
 }

 // 完成绘制
 function finishDrawing() {
   if (currentMode === 'area' && points.length > 2) {
     // 闭合多边形
     points.push(points[0]);
     lines.clearLayers();
     L.polygon(points, {
       color: colors.primary,
       weight: 2,
       fillColor: colors.primary,
       fillOpacity: 0.2,
       interactive: false
     }).addTo(lines);
   }

   if (tempLine) {
     lines.removeLayer(tempLine);
     tempLine = null;
   }

   calculateMeasurement();
   isMeasuring = false;
 }

 // 重置状态
 function reset() {
   isMeasuring = true;  // 保持测量状态
   points = [];
   tempPoint = null;
   if (tempLine) {
     lines.removeLayer(tempLine);
     tempLine = null;
   }
 }

 // 初始化事件监听
 function initEvents() {
   // 移除旧的事件监听
   if (mouseMoveHandler) mapObj.off('mousemove', mouseMoveHandler);
   if (clickHandler) mapObj.off('click', clickHandler);
   if (dblClickHandler) mapObj.off('dblclick', dblClickHandler);
   // 添加新的事件监听，设置bubbling为true
   mouseMoveHandler = (e) => {
     if (isMeasuring) {
       tempPoint = e.latlng;
       updateTempLine(e.latlng);
       calculateMeasurement(e.latlng);
     }
   };
   clickHandler = (e) => {
     if (isMeasuring) {
       e.originalEvent.stopPropagation(); // 阻止事件冒泡
       addPoint(e.latlng);
       calculateMeasurement();
     }
   };
   dblClickHandler = (e) => {
     if (isMeasuring && points.length > 1) {
       e.originalEvent.stopPropagation(); // 阻止事件冒泡
       finishDrawing();
     }
   };
   mapObj.on('mousemove', mouseMoveHandler, {bubbling: true});
   mapObj.on('click', clickHandler, {bubbling: true});
   mapObj.on('dblclick', dblClickHandler, {bubbling: true});
 }

 // 初始化
 initEvents();

 // 测量API
 return {
   /**
    * 测量距离
    */
   measureDistance() {
     reset();
     currentMode = 'distance';
     markers.clearLayers();
     lines.clearLayers();
     showResult('点击地图开始测量距离，双击结束');
   },

   /**
    * 测量面积
    */
   measureArea() {
     reset();
     currentMode = 'area';
     markers.clearLayers();
     lines.clearLayers();
     showResult('点击地图开始测量面积，双击结束');
   },

   /**
    * 清除测量
    */
   clearMeasurements() {
     isMeasuring = false;  // 完全停止测量
     currentMode = null;
     points = [];
     tempPoint = null;
     if (tempLine) {
       lines.removeLayer(tempLine);
       tempLine = null;
     }
     markers.clearLayers();
     lines.clearLayers();
     hideResult();
   },

   /**
    * 更新主题样式
    */
   updateTheme() {
     colors = themeColors[getTheme()];
     if (resultDiv) {
       resultDiv.style.backgroundColor = colors.bg;
       resultDiv.style.color = colors.text;
       resultDiv.style.borderColor = colors.primary;
     }
   },

   /**
    * 销毁测量工具
    */
   destroy() {
     if (mouseMoveHandler) mapObj.off('mousemove', mouseMoveHandler);
     if (clickHandler) mapObj.off('click', clickHandler);
     if (dblClickHandler) mapObj.off('dblclick', dblClickHandler);
     markers.remove();
     lines.remove();
     if (resultDiv) resultDiv.remove();
   }
 };
}
